#include "dwgcircle.h"
#include <cmath>


void calculateCircle(const QPoint& p1, const QPoint& p2, const QPoint& p3, QPoint& center, double& radius) {
    double x1 = p1.x();
    double y1 = p1.y();
    double x2 = p2.x();
    double y2 = p2.y();
    double x3 = p3.x();
    double y3 = p3.y();

    double temp = x2 * x2 + y2 * y2;
    double bc = (x1 * x1 + y1 * y1 - temp) / 2.0;
    double cd = (temp - x3 * x3 - y3 * y3) / 2.0;

    double det = (x1 - x2) * (y2 - y3) - (x2 - x3) * (y1 - y2);

    if (std::abs(det) < 1e-6) {

        center = QPoint(0, 0);
        radius = 0;
        return;
    }

    double idet = 1 / det;

    double centerX = (bc * (y2 - y3) - cd * (y1 - y2)) * idet;
    double centerY = ((x1 - x2) * cd - (x2 - x3) * bc) * idet;

    center = QPoint(static_cast<int>(centerX), static_cast<int>(centerY));
    radius = std::sqrt((centerX - x1) * (centerX - x1) + (centerY - y1) * (centerY - y1));
}

DwgCircle::DwgCircle()
{
}

void DwgCircle::Draw(QPainter *p)
{
    QPoint center;
    double radius;
    calculateCircle(mPoint1, mPoint2, mPoint3, center, radius);
    if (radius > 0) {
        p->drawEllipse(center, static_cast<int>(radius), static_cast<int>(radius));
    }
}


void DwgCircle::SetData(QPoint pt1, QPoint pt2)
{
}